package logic

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"order_srv/models"

	"order_srv/internal/svc"
	"order_srv/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderCreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderCreateLogic {
	return &OrderCreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderCreateLogic) OrderCreate(in *order.OrderCreateRequest) (*order.OrderCreateResponse, error) {
	var err error
	var u models.User
	u.ID = uint(in.UserId)
	if err = u.FindUserById(); err != nil {
		logx.Error("获取用户信息失败")
		return nil, err
	}
	if u.ID == 0 {
		logx.Error("用户不存在，创建订单失败")
		return nil, errors.New("用户不存在，创建订单失败")
	}

	var g models.Goods
	g.ID = uint(in.GoodsId)

	if err = g.FindGoodsById(); err != nil {
		logx.Error("获取商品信息失败")
		return nil, err
	}
	if g.ID == 0 {
		logx.Error("商品不存在，创建订单失败")
		return nil, errors.New("商品不存在，创建订单失败")
	}

	if g.Num < int(in.OrderNum) {
		logx.Error("库存不足")
		return nil, errors.New("库存不足")
	}
	o := models.Order{
		UserId:     int(in.UserId),
		OrderSn:    uuid.NewString(),
		OrderTotal: g.Price * float64(in.OrderNum),
		OrderNum:   int(in.OrderNum),
	}
	err = o.Create()
	if err != nil {
		logx.Error("创建订单失败")
		return nil, err
	}

	//创建订单商品
	og := models.OrderGoods{
		OrderId:         int(o.ID),
		GoodsId:         int(g.ID),
		OrdergoodsTitle: g.Title,
		OrdergoodsPrice: g.Price,
		OrdergoodsNum:   o.OrderNum,
	}
	err = og.Create()
	if err != nil {
		logx.Error("创建订单失败")
		return nil, err
	}
	return &order.OrderCreateResponse{
		OrderId: int64(o.ID),
	}, nil
}
